import { defineStore } from 'pinia';
import { getUserInfo, wxappAuth } from "@/api/user";
import { wechatAuth } from '@/api/public';


interface AuthState {
    token?: string;
    user: Record<string, any>;
}

export const useAuthStore = defineStore({
    id: 'auth',
    state: (): AuthState => ({
        token: undefined,
        user: {},
    }),
    getters: {
        isLogin(): boolean {
            const token = this.token || uni.getStorageSync('token') ;
            return !!token;
        },
    },
    actions: {
        setToken(value){
            this.token = value;
            uni.setStorageSync('token', value)
        },
        // 登录
        login() {
            return new Promise<void>((resolve) => {
                uni.login({
                    provider: 'weixin',
                    success: (loginRes) => {
                        // console.log(loginRes);
                        // 获取用户信息
                        uni.getUserInfo({
                            provider: 'weixin',
                            success: (infoRes) => {
                                // console.log('用户昵称为：', infoRes);

                                this.codeAuth(loginRes.code)
                                // codeAuth({
                                //     code: loginRes.code,
                                //     encryptedData: infoRes.encryptedData,
                                //     iv: infoRes.iv,
                                //     spread: ''
                                // }).then((res) => {
                                //     const resToken = res?.data?.token;
                                //     // console.log('res', res, 'res.data.data.token', resToken)
                                //     this.setToken(resToken)
                                //     // console.log('this.token', resToken)
                                //     uni.setStorageSync('token', resToken);
                                //     this.getUserInfo();
                                // })
                            }
                        });
                    }
                });
            });
        },
        async codeAuth(code) {
            // console.log("获取微信授权", code);
            try {
                return await new Promise((resolve, reject) => {
                    wechatAuth(code, "0", "1")
                      .then(({ data: data_1 }) => {
                          this.token = data_1.token;
                          this.setToken(data_1.token);
                          // console.log("微信公众号授权登录，获取用户信息");
                          // 获取用户信息;
                          this.getUserInfo();
                      })
                      .catch(reject);
                });
            } catch (error) {
                // console.log(error);
            }
        },
        getUserInfo() {
            return new Promise<void>((resolve) => {
                getUserInfo().then(resInfo => {
                    // console.log('resInfo', resInfo)
                    this.user = resInfo.data;
                    resolve();
                })
            });
        },
        layout() {
            this.token = undefined;
            this.user = {};
        },
    },
    // 本地持久化存储
    persist: {
        storage: {
            getItem: uni.getStorageSync,
            setItem: uni.setStorageSync,
        },
    },
});
